<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Articles Manager
 * @author	Tran Van Thanh
 * @mail	thanhtran@vietnambiz.com
 * @date	06.09.2011
 */
require_once('admin'.EXT);

class Articles extends Admin {

	function __construct()
	{
		parent::__construct();
		$this->load->model(array('articles_model'));
		$this->load->helper(array('upload','text'));			
	}

	function index()
	{
		$page = (isset($_GET['p']) && is_numeric($_GET['p'])) ? $_GET['p'] : 1;

        if(isset($_GET['status'])) {
            $status = ($_GET['status'] == 'active') ? 'yes' : 'no';
            $this->db->where('status', $status);
        }		
		if(isset($_GET['keyword'])) {    
			$keyword = $_GET['keyword'];
			$keyword = strip_tags($keyword);
			if($keyword == 'keyword')
			{
				$keyword = "";
			}
			else
			{
				$this->db->like('title', $keyword)
            		 ->or_like('description', $keyword)
            		 ->or_like('contents', $keyword)
            		 ->or_like('author', $keyword)
            		 ->or_like('source', $keyword);
			}
        }

		$this->data['articles'] 	= $this->articles_model->get_articles($page != "" ? $page : 1);
		$this->data['page'] 		= $page;

    	$conf =	array(
    		'base_url'		=> admin_url($this->router->class).'/',
    		'total_rows'	=> $this->articles_model->count_all(),
    		'per_page'		=> $this->config->item('articles', 'limit'),
    		'cur_page'		=> $page,
    	);
    	$this->pagination->initialize($conf);
    	$this->data['pagnav'] = $this->pagination->display_query_string();

		if($this->input->is_ajax_request()) {
			$this->load->view('articles/list', $this->data);
		}
		else {
			$this->data['tpl_file']	= 'articles/index';
			$this->load->view('layout/default', $this->data);
		}
	}

	function add()
	{		
		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
			$this->form_validation->set_message('required', '%s không hợp lệ!');
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {            	
            	$title 	= $this->input->post('txt_title');
            	$id_product =  strip_tags($this->input->post('txt_id_product'));

            	if($this->articles_model->check_id_products($id_product)==TRUE)
                {
            		$data = array(
            			'title'				=> strip_tags($title),
            			'title_link'		=> ascii_link($title,'-'),
            			'description'		=> strip_tags($this->input->post('txt_desc')),
            			'contents'			=> $this->input->post('txt_content'),
            			'author'			=> strip_tags($this->input->post('txt_author')),
            			'source'			=> strip_tags($this->input->post('txt_source')),            			         		
            			'date_create'		=> date('Y-m-d H:i:s'),            			
            			'news_works'		=> ($this->input->post('cck_News_works') == 'on') ? 'yes' : 'no',            		          			        		
            			'news_recruitment'	=> ($this->input->post('cck_news_recruitment') == 'on') ? 'yes' : 'no',
            			'status'			=> $this->input->post('status')
            		);
            			            		
            		$articles_id = $this->articles_model->insert($data);
            		
            		//Insert ID_articles and ID_Procducts into table articles_products
            		$arr_id_products = explode(",",$id_product);
            		foreach($arr_id_products as $k => $v)
            		{
	            		$arr_data = array(
	            			'id_articles'	=> $articles_id,
	            			'id_product'	=> $v
	            		);	 
	            		$this->db->insert('articles_products', $arr_data);           		
            		}
            		
            		// Upload images
            		if(isset($_FILES['images']['name']))
            		{
	            		$tt = count($_FILES['images']['name']);            		
	
	            		$album_dir = 'uploads/news/'.$articles_id.'/';
	            		create_dir($album_dir);
	
	            		for($i = 0; $i < $tt; $i++) 
	            		{
	            		    $ext = get_ext($_FILES["images"]["name"][$i]);
	                    	if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
	                    		continue;
	                    	}	            			
	
	            		    if($_FILES['images']['error'][$i] === 0) 
	            		    {
						        $new_path = $album_dir.$_FILES["images"]["name"][$i];
						        move_uploaded_file($_FILES["images"]['tmp_name'][$i], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);
	
						        $data = array(
						        	'name'				=> $_FILES["images"]["name"][$i],
						        	'name_link'			=> ascii_link($_FILES["images"]["name"][$i],'-'),					        	
						        	'img_path'			=> $this->_create_thumb($new_path),
						        	'id_articles'		=> $articles_id,	
						        	'date_create'		=> date('Y-m-d H:i:s'),
						        	'user_create'		=> $_SESSION['_admin']['username'],
						        );
	
						        $this->db->insert('images_news', $data);
	            			}
	            		}
            		}

            		die('yes');
                }
                else
                {
                	die('ID sản phẩm không tồn tại, hãy kiểm tra lại!');
                }            	
            }
            else {
            	die(validation_errors());
            }
		}
		
		$this->load->view('articles/add', $this->data);
	}

	function edit($articles_id = null)
	{		
		$articles = $this->articles_model->get($articles_id);
		
		$images = $this->articles_model->get_images($articles_id);

		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
    		$this->form_validation->set_rules('txt_title', 'Tiêu đề', 'required|trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {       
            	$title 	= $this->input->post('txt_title');
            	$id_product =  strip_tags($this->input->post('txt_id_product'));

            	$data_articles = array(
            		'title'				=> strip_tags($title),
            		'title_link'		=> ascii_link($title,'-'),
            		'description'		=> strip_tags($this->input->post('txt_desc')),
            		'contents'			=> $this->input->post('txt_content'),
            		'author'			=> strip_tags($this->input->post('txt_author')),
            		'source'			=> strip_tags($this->input->post('txt_source')),            		
            		'news_works'		=> ($this->input->post('cck_News_works') == 'on') ? 'yes' : 'no',
            		'news_recruitment'	=> ($this->input->post('cck_news_recruitment') == 'on') ? 'yes' : 'no',            		          			        		
            		'status'			=> $this->input->post('status')
            	);            	
            	
            	$this->articles_model->update($articles_id,$data_articles);
            	
            	//Delete all where id_articles into table articles_products
            	$this->db->delete('articles_products', array('id_articles' => $articles_id));           	 	            	
				
            	//Update ID_articles and ID_Procducts into table articles_products
            	$arr_id_products = explode(",",$id_product);
            	
            	foreach($arr_id_products as $k => $v)
            	{
            		$arr_data = array(
            			'id_articles'	=> $articles_id,
            			'id_product'	=> $v
            		);	 
            		$this->db->insert('articles_products', $arr_data);           		
            	}

            	$images_id 			= $this->input->post('images_id');             	          
            	$album_dir 			= 'uploads/news/'.$articles_id.'/';
            	
            	//Delete all images with id_articles
            	$this->db->delete('images_news', array('id_articles' => $articles_id));            	            	
            	
            	// Upload images
            	if(isset($_FILES['images']['name']))
            	{
            		$tt = count($_FILES['images']['name']);            		

            		$album_dir = 'uploads/news/'.$articles_id.'/';
            		if(!is_dir($album_dir))
            		{
            			create_dir($album_dir);
            		}            		

            		for($i = 0; $i < $tt; $i++) 
            		{
            		    $ext = get_ext($_FILES["images"]["name"][$i]);
                    	if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
                    		continue;
                    	}

            		    if($_FILES['images']['error'][$i] === 0) 
            		    {
					        $new_path = $album_dir.$_FILES["images"]["name"][$i];
					        move_uploaded_file($_FILES["images"]['tmp_name'][$i], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);

					        $data = array(
					        	'name'				=> $_FILES["images"]["name"][$i],
					        	'name_link'			=> ascii_link($_FILES["images"]["name"][$i],'-'),					        	
					        	'img_path'			=> $this->_create_thumb($new_path),
					        	'id_articles'		=> $articles_id,	
					        	'date_create'		=> date('Y-m-d H:i:s'),
					        	'user_create'		=> $_SESSION['_admin']['username'],
					        );

					        $this->db->insert('images_news', $data);
            			}
            		}
            	}
            	        	
            	die('yes');            	            	            	
            }
            else {
            	die(validation_errors());
            }
		}

		$this->data['articles'] = $articles;
		$this->data['images'] 	= $images;
		$this->load->view('articles/edit', $this->data);
	}
	
    function delete($articles_id = null)
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        	$images = $this->articles_model->get_images($articles_id);
        	if(count($images) > 0) {
        		foreach($images as $i => $image) {
        			$this->_delete_image($image->img_path);
        		}
        	}

            $this->articles_model->delete_articles($articles_id);

            // Remove dir
            if(is_numeric($articles_id)) {
            	$a = array($articles_id); $articles_id = $a;
            }

            foreach($articles_id as $id) {
            	remove_dir('uploads/news/'.$id);
            }

            die('yes');
        }
    }

	function do_action()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST') {

			$id_list = $this->input->post('id');
			$action = $this->input->post('action');

			if($action == 'delete') {
				$this->delete($id_list);
			}
			elseif($action == 'pending') {
				$this->articles_model->update_many($id_list, array('status' => 'no'));
			}
			elseif($action == 'active') {
				$this->articles_model->update_many($id_list, array('status' => 'yes'));
			}

			die('yes');
		}
	}

	function change_status()
	{
		$articles_id = $this->input->post('articles_id');
		$status 	 = $this->input->post('status');

		$this->articles_model->update($articles_id, array('status' => $status));
		die('yes');
	}	

	function load_row($articles_id = null)
	{		
		$this->data['articles'] = $this->articles_model->get($articles_id);
		$this->load->view('articles/row', $this->data);
	}

	function _check_upload()
	{
		$count = 0;
		if(isset($_FILES['images'])) {
	    	$tt = count($_FILES['images']['name']);
	    	for($i = 0; $i < $tt; $i++) {
	    	    if($_FILES['images']['error'][$i] === 0) $count++;
	    	}
	    }

	    return ($count > 0) ? true : false;
	}

	function _create_thumb($img_path = '')
	{
		$sizes = config_item('thumb_size');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		
		if($img = $this->db->from('images_news')->where('img_path',$pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name)->get()->row())
		{
			$temp	=	explode('.',$pathinfo['basename']);
			$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];
		}

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}


		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}
	
	function _delete_image($img_path = '')
	{
    	$filename = basename($img_path);
        $sizes = config_item('thumb_size');

    	foreach($sizes as $size) {
    		$path = str_replace($sizes[0], $size, $img_path);
    		if(is_file($path)) unlink($path);
    	}
    	$path = str_replace('/thumb_'.$sizes[0], '', $img_path);
    	if(is_file($path)) unlink($path);
	}
	
	function deleteAll($directory, $empty = false) { 
    if(substr($directory,-1) == "/") { 
        $directory = substr($directory,0,-1); 
    } 

    if(!file_exists($directory) || !is_dir($directory)) { 
        return false; 
    } elseif(!is_readable($directory)) { 
        return false; 
    } else { 
        $directoryHandle = opendir($directory); 
        
        while ($contents = readdir($directoryHandle)) { 
            if($contents != '.' && $contents != '..') { 
                $path = $directory . "/" . $contents; 
                
                if(is_dir($path)) { 
                    deleteAll($path); 
                } else { 
                    unlink($path); 
                } 
            } 
        } 
        
        closedir($directoryHandle); 

        if($empty == false) { 
            if(!rmdir($directory)) { 
                return false; 
            } 
        } 
        
        return true; 
    } 
} 
	
	 
}

